package org.jeecg.modules.business.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.dto.CouponsGenerateDto;
import org.jeecg.modules.business.dto.PostDataDto;
import org.jeecg.modules.business.entity.BusMarketCoupons;
import org.jeecg.modules.business.entity.BusMarketCouponsCashUsed;
import org.jeecg.modules.business.entity.BusMarketMealCoupons;
import org.jeecg.modules.business.entity.BusMarketMealCouponsUsed;
import org.jeecg.modules.business.enums.CouponsStatusEnum;
import org.jeecg.modules.business.service.IBusMarketCouponsService;
import org.jeecg.modules.business.service.IBusMarketMealCouponsService;
import org.jeecg.modules.business.service.IBusMarketMealCouponsUsedService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.business.vo.MealCouponStatVo;
import org.jeecg.modules.business.vo.MemberCardStatVo;
import org.jeecg.modules.rooms.entity.CesMealCoupon;
import org.jeecg.modules.rooms.entity.CesStockType;
import org.jeecg.modules.rooms.service.CesMealCouponServiceImpl;
import org.jeecg.modules.rooms.service.CesStockTypeServiceImpl;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: bus_market_meal_coupons_used
 * @Author: jeecg-boot
 * @Date:   2023-03-14
 * @Version: V1.0
 */
@Api(tags="bus_market_meal_coupons_used")
@RestController
@RequestMapping("/business/busMarketMealCouponsUsed")
@Slf4j
public class BusMarketMealCouponsUsedController extends JeecgController<BusMarketMealCouponsUsed, IBusMarketMealCouponsUsedService> {
	@Autowired
	private IBusMarketMealCouponsUsedService busMarketMealCouponsUsedService;
	 @Autowired
	 private IBusMarketMealCouponsService busMarketMealCouponsService;
	 @Autowired
	 private CesMealCouponServiceImpl cesMealCouponService;
	 @Autowired
	 private ISysUserService sysUserService;
	/**
	 * 分页列表查询
	 *
	 * @param busMarketMealCouponsUsed
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "bus_market_meal_coupons_used-分页列表查询")
	@ApiOperation(value="bus_market_meal_coupons_used-分页列表查询", notes="bus_market_meal_coupons_used-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusMarketMealCouponsUsed>> queryPageList(BusMarketMealCouponsUsed busMarketMealCouponsUsed,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BusMarketMealCouponsUsed> queryWrapper = QueryGenerator.initQueryWrapper(busMarketMealCouponsUsed, req.getParameterMap());
		Page<BusMarketMealCouponsUsed> page = new Page<BusMarketMealCouponsUsed>(pageNo, pageSize);
		IPage<BusMarketMealCouponsUsed> pageList = busMarketMealCouponsUsedService.page(page, queryWrapper);
		pageList.getRecords().forEach(item -> {
			BusMarketMealCoupons coupons = busMarketMealCouponsService.getById(item.getCouponsId());
			if (coupons != null) {
				item.setCouponsName(coupons.getName());
				item.setCost(coupons.getCost());
				if (ObjectUtils.isNotEmpty(coupons.getType())) {
					CesMealCoupon cesMealCoupon = cesMealCouponService.getById(coupons.getType());
					if (cesMealCoupon != null) {
						item.setTypeName(cesMealCoupon.getName());
					}
				}
			}
			CouponsStatusEnum couponsStatusEnum = CouponsStatusEnum.val(item.getStatus());
			if (couponsStatusEnum != null) {
				item.setStatusName(couponsStatusEnum.getTitle());
			}
			if (ObjectUtils.isNotEmpty(item.getUsedUserId())) {
				SysUser sysUser = sysUserService.getById(item.getUsedUserId());
				if (sysUser != null) {
					item.setUsedUserName(sysUser.getUsername());
				}
			}
		});
		return Result.OK(pageList);
	}

	 /**
	  * 核销列表
	  * @param pageNo
	  * @param pageSize
	  * @param hotelId
	  * @param type
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="核销列表", notes="核销列表")
	 @GetMapping(value = "/verifyList")
	 public Result<IPage<BusMarketMealCouponsUsed>> verifyPageList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																   @RequestParam(name="hotelId", required = true) String hotelId,
																   @RequestParam(name="type", defaultValue="") String type,
																  HttpServletRequest req) {
		 Page<BusMarketMealCouponsUsed> page = new Page<BusMarketMealCouponsUsed>(pageNo, pageSize);
		 IPage<BusMarketMealCouponsUsed> pageList = busMarketMealCouponsUsedService.verifyList(page, hotelId, type);
		 pageList.getRecords().forEach(item -> {
			 if (ObjectUtils.isNotEmpty(item.getUsedUserId())) {
				 SysUser sysUser = sysUserService.getById(item.getUsedUserId());
				 if (sysUser != null) {
					 item.setUsedUserName(sysUser.getUsername());
				 }
			 }
		 });
		 return Result.OK(pageList);
	 }

	 /**
	  * 核销各种统计
	  * @param hotelId
	  * @return
	  */
	 @GetMapping(value = "/stat")
	 public Result stat(@RequestParam(name="hotelId") String hotelId,@RequestParam(name="type",required = false) String type) {
		 MealCouponStatVo vo = busMarketMealCouponsUsedService.stat(hotelId,type);
		 return Result.OK(vo);
	 }

	/**
	 *   添加
	 *
	 * @param busMarketMealCouponsUsed
	 * @return
	 */
	@AutoLog(value = "bus_market_meal_coupons_used-添加")
	@ApiOperation(value="bus_market_meal_coupons_used-添加", notes="bus_market_meal_coupons_used-添加")
	//@RequiresPermissions("business:bus_market_meal_coupons_used:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusMarketMealCouponsUsed busMarketMealCouponsUsed) {
		busMarketMealCouponsUsedService.save(busMarketMealCouponsUsed);
		return Result.OK("添加成功！");
	}

	 /**
	  *   生成餐券
	  *
	  * @param dto
	  * @return
	  */
	 @AutoLog(value = "餐券领取使用表-生成")
	 @ApiOperation(value="餐券领取使用表-生成", notes="餐券领取使用表-生成")
	 @PostMapping(value = "/generate")
	 public Result<String> generate(@RequestBody CouponsGenerateDto dto) {
		 Result res = busMarketMealCouponsUsedService.generate(dto);
		 return res;
	 }

	 /**
	  * 核销
	  * @param dto
	  * @return
	  */
	 @AutoLog(value = "核销")
	 @ApiOperation(value="核销", notes="核销")
	 @RequestMapping(value = "/verify", method = {RequestMethod.POST})
	 public Result<String> verify(@RequestBody PostDataDto dto) {
		 BusMarketMealCouponsUsed busMarketMealCouponsUsed = busMarketMealCouponsUsedService.getById(dto.getId());
		 if (busMarketMealCouponsUsed == null) {
			 return Result.error("此券不存在!");
		 }
		 if (busMarketMealCouponsUsed.getStatus() != CouponsStatusEnum.received.getKey()) {
			 CouponsStatusEnum couponsStatusEnum = CouponsStatusEnum.val(busMarketMealCouponsUsed.getStatus());
			 String statusName = "";
			 if (couponsStatusEnum != null) {
				 statusName = couponsStatusEnum.getTitle();
			 }
			 return Result.error("此券状态" + statusName + ",不可核销!");
		 }
		 BusMarketMealCoupons busMarketMealCoupons = busMarketMealCouponsService.getById(busMarketMealCouponsUsed.getCouponsId());
		 if (busMarketMealCoupons == null) {
			 return Result.error("此券活动不存在!");
		 }
		 CesMealCoupon cesMealCoupon = cesMealCouponService.getById(busMarketMealCoupons.getType());
		 if (cesMealCoupon == null) {
			 return Result.error("此券类型不存在!");
		 }
		 DateTime dateTime = DateTime.now();
		 DateFormat startDateFormat = new SimpleDateFormat("yyyy-MM-dd " + cesMealCoupon.getStartDate().trim());
		 String startDateStr = startDateFormat.format(dateTime);
		 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		 try {
			 if (dateTime.compareTo(dateFormat.parse(startDateStr)) < 0) {
				 return Result.error("此券未到核销时间!");
			 }
		 } catch (ParseException e) {
			 return Result.error("此券类型开始时间格式错误!");
		 }

		 DateFormat endDateFormat = new SimpleDateFormat("yyyy-MM-dd " + cesMealCoupon.getEndDate().trim());
		 String endDateStr = endDateFormat.format(dateTime);
		 try {
			 if (dateTime.compareTo(dateFormat.parse(endDateStr)) > 0) {
				 return Result.error("此券已超过核销时间!");
			 }
		 } catch (ParseException e) {
			 return Result.error("此券类型截至时间格式错误!");
		 }
		 LoginUser user = TokenUtils.getAuthUser();
		 LambdaUpdateWrapper<BusMarketMealCouponsUsed> updateWrapper = new UpdateWrapper().lambda();
		 updateWrapper.set(BusMarketMealCouponsUsed::getStatus, CouponsStatusEnum.used.getKey());
		 updateWrapper.set(BusMarketMealCouponsUsed::getUsedUserId, user.getId());
		 updateWrapper.set(BusMarketMealCouponsUsed::getUsedTime, DateTime.now());
		 updateWrapper.eq(BusMarketMealCouponsUsed::getId, dto.getId());
		 busMarketMealCouponsUsedService.update(updateWrapper);
		 return Result.OK("编辑成功!");
	 }
	
	/**
	 *  编辑
	 *
	 * @param busMarketMealCouponsUsed
	 * @return
	 */
	@AutoLog(value = "bus_market_meal_coupons_used-编辑")
	@ApiOperation(value="bus_market_meal_coupons_used-编辑", notes="bus_market_meal_coupons_used-编辑")
	//@RequiresPermissions("business:bus_market_meal_coupons_used:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusMarketMealCouponsUsed busMarketMealCouponsUsed) {
		busMarketMealCouponsUsedService.updateById(busMarketMealCouponsUsed);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "bus_market_meal_coupons_used-通过id删除")
	@ApiOperation(value="bus_market_meal_coupons_used-通过id删除", notes="bus_market_meal_coupons_used-通过id删除")
	//@RequiresPermissions("business:bus_market_meal_coupons_used:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		busMarketMealCouponsUsedService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "bus_market_meal_coupons_used-批量删除")
	@ApiOperation(value="bus_market_meal_coupons_used-批量删除", notes="bus_market_meal_coupons_used-批量删除")
	//@RequiresPermissions("business:bus_market_meal_coupons_used:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.busMarketMealCouponsUsedService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "bus_market_meal_coupons_used-通过id查询")
	@ApiOperation(value="bus_market_meal_coupons_used-通过id查询", notes="bus_market_meal_coupons_used-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusMarketMealCouponsUsed> queryById(@RequestParam(name="id",required=true) String id) {
		BusMarketMealCouponsUsed busMarketMealCouponsUsed = busMarketMealCouponsUsedService.getById(id);
		if(busMarketMealCouponsUsed==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busMarketMealCouponsUsed);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param busMarketMealCouponsUsed
    */
    //@RequiresPermissions("business:bus_market_meal_coupons_used:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusMarketMealCouponsUsed busMarketMealCouponsUsed) {
        return super.exportXls(request, busMarketMealCouponsUsed, BusMarketMealCouponsUsed.class, "bus_market_meal_coupons_used");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_market_meal_coupons_used:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BusMarketMealCouponsUsed.class);
    }

}
